import { getMenus, MenuItemOld } from "@/api";
import { Menu, MenuProps } from "antd";
import Sider from "antd/es/layout/Sider";
import { FC, useEffect, useState } from "react";
import "./index.module.less";
import { FolderOutlined, UserOutlined } from "@ant-design/icons";
import { useLocation, useNavigate } from "react-router-dom";
interface SiderLayoutProps {
  collapsed: boolean;
}
type MenuItem = Required<MenuProps>["items"][number];

const SiderLayout: FC<SiderLayoutProps> = ({ collapsed }) => {
  const [items, setItems] = useState<MenuItem[]>([]);
  const navigate = useNavigate();
  const location = useLocation();
  const transformData = (data: MenuItemOld[]): MenuItem[] => {
    return data.map((item) => ({
      key: item.children.length > 0?item.id.toString():item.path,
      label: item.authName,
      path: item.path,
      children: item.children.length > 0 ? transformData(item.children) : "",
      icon: item.children.length > 0 ? <UserOutlined /> : <FolderOutlined />,
    }));
  };
  
  const getMenuData = async () => {
    const res = await getMenus();
    setItems(transformData(res.data));
  };
  
  useEffect(() => {
    getMenuData();
    // eslint-disable-next-line react-hooks/exhaustive-deps
  }, []);

  return (
    <>
      <Sider width={200} trigger={null} collapsible collapsed={collapsed}>
        <h2 style={{ color: "#fff", textAlign: "center" }}>
          {!collapsed ? "电商后台管理系统" : "后台"}
        </h2>
        <Menu
          style={{ fontSize: "16px" }}
          theme="dark"
          mode="inline"
          items={items}
          selectedKeys={[location.pathname.split("/")[1]]}
          onClick={(e) => navigate(e.key)}
        />
      </Sider>
    </>
  );
};
export default SiderLayout;
